package cn.org.eshow.dao.hibernate;

import cn.org.eshow.bean.query.ProductCommentQuery;
import cn.org.eshow.common.dao.EnhancedRule;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.dao.ProductCommentDao;
import cn.org.eshow.model.ProductComment;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("productCommentDao")
public class ProductCommentDaoHibernate extends GenericDaoHibernate<ProductComment, Integer> implements ProductCommentDao {

    public ProductCommentDaoHibernate() {
        super(ProductComment.class);
    }

    @Override
    public List<ProductComment> list(ProductCommentQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        return list(rule);
    }

    @Override
    public Page<ProductComment> search(ProductCommentQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        if (query != null) {
            rule.setOffset(query.getOffset());
            rule.setPageSize(query.pagesize);
        }
        return page(rule);
    }

    @Override
    public Long count(ProductCommentQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        return count(ProductComment.class, rule);
    }

    public EnhancedRule setRule(EnhancedRule rule, ProductCommentQuery query) {
        if (query != null) {
            if (query.startAddTime != null) {
                rule.add(Restrictions.ge("addTime", query.startAddTime));
            }
            if (query.endAddTime != null) {
                rule.add(Restrictions.le("addTime", query.endAddTime));
            }
            if (query.content != null) {
                rule.add(Restrictions.like("content", query.content, MatchMode.ANYWHERE));
            }
            if (query.comment != null) {
                rule.add(Restrictions.eq("comment", query.comment));
            }
            if (query.enabled != null) {
                rule.add(Restrictions.eq("enabled", query.enabled));
            }
            if (query.productItemId != null) {
                rule.add(Restrictions.eq("productItem.id", query.productItemId));
            }
            if (query.productOrderId != null) {
                rule.add(Restrictions.eq("productOrder.id", query.productOrderId));
            }
            if (query.productId != null) {
                rule.add(Restrictions.eq("product.id", query.productId));
            }
            if (query.userId != null) {
                rule.add(Restrictions.eq("user.id", query.userId));
            }
            if (!StringUtils.isEmpty(query.getOrder())) {
                rule.addOrder(query.getDesc() ? Order.desc(query.getOrder()) : Order.asc(query.getOrder()));
            }
        }
        return rule;
    }
}
